<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
use PHPMailer\PHPMailer\PHPMailer;
use think\facade\Env;

header('Access-Control-Allow-Origin:*');
// 响应类型
header('Access-Control-Allow-Methods:*');
// 响应头设置
header('Access-Control-Allow-Headers:x-requested-with,content-type');

function getDescription() {
    $title_all = model('admin/Toolslist')->where('status', 1)->column('title');
    return implode(',', $title_all);
}

function getFullUrl($url) {
    $preg = "/^http(s)?:\\/\\/.+/";
    if (preg_match($preg, $url)) {
        return $url;
    } else {
        return request()->domain() . '/' . $url;
    }
}

function get_date() {
    return date('Y-m-d');
}

function get_datetime() {
    return date('Y-m-d h:i:s');
}

function send_mail($receive_mail, $type = 0) {
    $sendInfo = get_mailContent($type);
    // 实例化PHPMailer核心类
    $mail = new PHPMailer();
    // 是否启用smtp的debug进行调试 开发环境建议开启 生产环境注释掉即可 默认关闭debug调试模式
    $mail->SMTPDebug = 0;
    // 使用smtp鉴权方式发送邮件
    $mail->isSMTP();
    // smtp需要鉴权 这个必须是true
    $mail->SMTPAuth = true;
    // 链接qq域名邮箱的服务器地址
    $mail->Host = session('sys.smtp_addr');
    // 设置使用ssl加密方式登录鉴权
    $mail->SMTPSecure = 'ssl';
    // 设置ssl连接smtp服务器的远程服务器端口号
    $mail->Port = session('sys.smtp_port');
    // 设置发送的邮件的编码
    $mail->CharSet = 'UTF-8';
    // 设置发件人昵称 显示在收件人邮件的发件人邮箱地址前的发件人姓名
    $mail->FromName = session('sys.mailer');
    // smtp登录的账号 QQ邮箱即可
    $mail->Username = session('sys.smtp_login');
    // smtp登录的密码 使用生成的授权码
    $mail->Password = session('sys.smtp_pass');
    // 设置发件人邮箱地址 同登录账号
    $mail->From = session('sys.send_mail');
    // 邮件正文是否为html编码 注意此处是一个方法
    $mail->isHTML(true);
    // 设置收件人邮箱地址 $mail->addAddress('569349741@qq.com');
    $receive_mail = explode(',', $receive_mail);
    foreach ($receive_mail as $r_mail) {
        $mail->addAddress($r_mail);
    }
    // 添加多个收件人 则多次调用方法即可
    //$mail->addAddress('87654321@163.com');
    // 添加该邮件的主题 $mail->Subject = '我就试试看(WJSSK)用户注册验证邮件';
    $mail->Subject = $sendInfo['title'];
    // 添加邮件正文 $mail->Body = '<h1>Hello World</h1>';
    $mail->Body = $sendInfo['content'];
    // 为该邮件添加附件
    //$mail->addAttachment('./example.pdf');
    // 发送邮件 返回状态
    try {
        $status = $mail->send();
        $rs = [
            'code' => 1,
            'msg' => '发送成功！',
            'data' => $status
        ];
    } catch (\PHPMailer\PHPMailer\Exception $e) {
        $rs = [
            'code' => 0,
            'msg' => '发送失败！Error:' . $e->getMessage(),
            'data' => []
        ];
    }
    return $rs;
}

function get_mailContent($type) {
    switch ($type) {
        default:
            $data['content'] = "邮箱配置测试！<br>如果您能看到这份邮箱，那么说明你的邮箱配置成功了！";
            $data['title'] = "邮箱配置测试";
            break;
    }
    return $data;
}

function getToolsType($code = '') {
    $type = config('admin_conf.tools_type');
    if (empty($code)) {
        return $type;
    } else {
        foreach ($type as $t) {
            if ($t['code'] == $code) {
                return $t['name'];
            }
        }
    }
}

function setImgToBase64($imgSrc) {
    $img_info = getimagesize($imgSrc);
    if ($img_info) {
        return "data:{$img_info['mime']};base64," . base64_encode(file_get_contents($imgSrc));
    } else {
        return false;
    }
}

function mkdirs($path, $mode = 0777) {
    if (is_dir($path) || @mkdir($path, $mode)) return TRUE;
    if (!mkdirs(dirname($path), $mode)) return FALSE;
    return @mkdir($path, $mode);
}

function downloadLocal($videoSrc) {
    $i = strpos($videoSrc, '?');
    $baseUrl = substr($videoSrc, 0, $i);

    $path_parts = pathinfo($baseUrl);
    $filePath = Env::get('runtime_path').$path_parts['extension'];
    mkdirs($filePath);

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $videoSrc);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.1 Safari/537.11');
    $res = curl_exec($ch);
    $rescode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    $savePath = $filePath."/".time().".".$path_parts['extension'];
    file_put_contents($savePath, $res); //write

    return uploadToSpace($savePath);
}

function getSpaceAccessToken($host = 'http://106.13.118.119'){
    $space_url = $host;
    $getATUrl = $space_url.'/?user/index/loginSubmit&name=admin&password=a2288215';
    $AT_info = json_decode(file_get_contents($getATUrl));
    if(isset($AT_info->data)&&$AT_info->data == 'ok'){
        set_php_file(Env::get('config_path').'Kod_accessToken.json',json_encode($AT_info));
        return $AT_info->info;
    }else{
        getSpaceAccessToken();
    }
}

function uploadToSpace($filePath, $getAT = false) {
    $space_url = 'http://106.13.118.119';
    if($getAT){
        $accessToken = getSpaceAccessToken($space_url);
    }else{
        $Kod_accessToken = get_php_file(Env::get('config_path').'Kod_accessToken.json');
        if(empty($Kod_accessToken)){
            uploadToSpace($filePath,true);
        }else{
            $accessToken = json_decode($Kod_accessToken)->info;
        }
    }
    $uploadSrc = $space_url.'?explorer/upload/fileUpload&accessToken='.$accessToken;

    $ch = curl_init();
    //目标服务器地址
    curl_setopt($ch, CURLOPT_URL, $uploadSrc);
    //设置上传的文件
    curl_setopt($ch, CURLOPT_POST, true);
    $data = array(
        'path' => '{source:23}/',
        'name' => basename($filePath),
        'file' => new CURLFile($filePath)
    );
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    // 对认证证书来源的检查
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    // 从证书中检查SSL加密算法是否存在
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
    //获取的信息以文件流的形式返回，而不是直接输出
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.1 Safari/537.11');

    $res = curl_exec($ch);
    curl_close($ch);
    $res = json_decode($res, true);

    if ($res['code'] == 10001) {
        uploadToSpace($filePath, true);
    }else{
        if($res['code']){
            return $space_url.'?explorer/index/fileOut&path='.$res['info'];
        }else{
            return ['code'=>false,'msg'=>$res['data']];
        }
    }
}

function get_php_file($filename) {
    if(file_exists($filename)){
        return trim(file_get_contents($filename));
    }else{
        return '';
    }

}

function set_php_file($filename, $content) {
    $fp = fopen($filename, "w");
    fwrite($fp, $content);
    fclose($fp);
}